package com.hrvsr.downloader.httpclient.session;

import java.util.Iterator;

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

import com.hrvsr.common.util.PropertyUtil;
import com.hrvsr.session.cookie.Cookie;
import com.hrvsr.session.cookie.Cookies;

/**
 * adapt httpclient cookieStore to Hrvsr cookies
 */
public class CookieStoreApater implements Cookies {

	private static final long serialVersionUID = 1L;

	/**
	 * read only
	 */
	private String cookiesUuid = PropertyUtil.getProperty("") + Math.random();

	private CookieStore cookieStore = new BasicCookieStore();

	@Override
	public String getCookiesUuid() {
		return cookiesUuid;
	}

	@Override
	public Iterator<Cookie> createIterator() {
		return new IteratorAdapter(cookieStore.getCookies().iterator());
	}

	/**
	 * actually Hrvsr Cookie never gets in real cookie read or write,<br/>
	 * it just offers an initial value, <br/>
	 * it's basic client cookie that really get in cookie read or write<br/>
	 * when httpclient performs the request <br>
	 * this add cookie converts a Hrvsr Cookie to a BasicClient cookie <br>
	 * and adds it to the httpclient cookie store
	 */
	@Override
	public void addCookie(Cookie cookie) {
		BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue());
		c.setDomain(cookie.getDomain());
		c.setPath(cookie.getPath());
		c.setExpiryDate(cookie.getExpiryDate());
		cookieStore.addCookie(c);
	}

	
	
	
	public CookieStore getCookieStore() {
		return cookieStore;
	}

	public void setCookieStore(CookieStore cookieStore) {
		this.cookieStore = cookieStore;
	}

//	public void setCookiesUuid(String cookiesUuid) {
//		this.cookiesUuid = cookiesUuid;
//	}




	static class IteratorAdapter implements Iterator<Cookie> {
		private Iterator<org.apache.http.cookie.Cookie> it;

		public IteratorAdapter(Iterator<org.apache.http.cookie.Cookie> it) {
			this.it = it;
		}

		@Override
		public boolean hasNext() {

			return it.hasNext();
		}

		@Override
		public Cookie next() {
			return new CookieAdapter(it.next());
		}

		@Override
		public void remove() {
			it.remove();
		}

	}

}
